package com.xiao.mall.foundation.datasource;

import lombok.extern.slf4j.Slf4j;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.DefaultTransactionStatus;

@Slf4j
public class JpaTransactionManagerEx extends JpaTransactionManager {
    @Override
    protected void doBegin(Object transaction, TransactionDefinition definition) {
        if (log.isDebugEnabled()) {
            log.debug("begin transaction: {}, definition:{}", transaction, definition);
        }

        if (definition.isReadOnly()) {
            DynamicRoutingDataSourceContext.useSlave();
        } else {
            DynamicRoutingDataSourceContext.useMaster();
        }

        if (log.isDebugEnabled()) {
            log.debug("using database: {} for transaction: {}, definition: {} .",
                    DynamicRoutingDataSourceContext.getDataSource(),
                    transaction,
                    definition);
        }

        super.doBegin(transaction, definition);
    }

    @Override
    protected void doCommit(DefaultTransactionStatus status) {
        super.doCommit(status);
    }
}
